package com.cloud.dynamic.gateway.repository;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author amber
 */
@Component
public class RedisRouteRepository implements RouteDefinitionRepository {


    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String GATEWAY_REDIS_KEY = "dynamic:gateway:rules";

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {

        List<RouteDefinition> collect = redisTemplate.opsForHash().values(GATEWAY_REDIS_KEY).stream().
                map(value -> JSONUtil.toBean(value.toString(), RouteDefinition.class)).
                collect(Collectors.toList());

        System.out.println("redis 获取 网关配置 " + collect);
        return Flux.fromIterable(collect);
    }


    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {

        return route.flatMap(routeDefinition -> {
            redisTemplate.opsForHash().put(GATEWAY_REDIS_KEY, routeDefinition.getId(), JSONUtil.toJsonStr(routeDefinition));
            return Mono.empty();
        });
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return routeId.flatMap(id -> {
            redisTemplate.opsForHash().delete(GATEWAY_REDIS_KEY, id);
            return Mono.defer(() -> Mono.error(
                    new NotFoundException("RouteDefinition not found: " + routeId)
            ));
        });
    }
}
